package com.example.njut;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

public class MyJson {
   static public ArrayList<Weather>getWeather(String str) throws Exception{
      ArrayList<Weather> arrayList = new ArrayList<>();

      JSONObject json = new JSONObject(str);


      JSONArray results = json.getJSONArray("results");
      JSONObject all = (JSONObject) results.get(0);

      //城市名称
      String city = all.getJSONObject("location").getString("name");

      //每日天气
      JSONArray daily = all.getJSONArray("daily");

      for(int i=0;i<daily.length();i++){
         Weather weather =new Weather();
         weather.setCity(city);
         JSONObject day = (JSONObject) daily.get(i);
         //日期
         String date = day.getString("date");
         weather.setDate(date);
         //白天天气
         String text_day = day.getString("text_day");
         weather.setText_day(text_day);
         //夜晚天气
         String text_night = day.getString("text_night");
         weather.setText_night(text_night);
         //最低气温
         String low = day.getString("low");
         weather.setLow(low);
         //最高气温
         String high = day.getString("high");
         weather.setHigh(high);

         arrayList.add(weather);
      }
     return arrayList;
   }

   static public ArrayList<NowWeather>getNowWeather(String str) throws Exception{
      ArrayList<NowWeather> arrayList = new ArrayList<>();

      JSONObject json = new JSONObject(str);

      JSONArray results = json.getJSONArray("results");
      JSONObject all = (JSONObject) results.get(0);

      String text = all.getJSONObject("now").getString("text");
      String temperature = all.getJSONObject("now").getString("temperature");
      NowWeather nowWeather = new NowWeather();

      nowWeather.setText(text);
      nowWeather.setTemperature(temperature);

      arrayList.add(nowWeather);

      return arrayList;
   }
}
